package com.wkh.common.app

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import com.wkh.common.R
import com.wkh.common.annotation.PrintMethod
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

/**
 * @des: Fragment的基类
 * @author: wkh
 * @version: 1.0.0
 * @date: 3/18/21 18:54
 * @see {@link }
 */
abstract class BaseFragment(@LayoutRes layoutRes: Int, isReuseView: Boolean = false) : Fragment(),
    CoroutineScope by MainScope() {

    protected lateinit var containerView: FrameLayout

    protected var loadingView: View? = null

    protected lateinit var rootView: View

    private var resourceId = layoutRes

    private var isReuseView = isReuseView


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        containerView = LayoutHelper.get().syncGet(R.layout.fragment_base) as FrameLayout
        containerView.parent?.run {
            (this as ViewGroup).removeView(containerView)
        }

        return containerView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        launch {
            loadingView = containerView.findViewById(R.id.fragmentLoadingView)
            loadingView?.visibility = View.VISIBLE
            rootView = LayoutHelper.get().asyncGet(resourceId)
            containerView.addView(rootView)

            initView()
            onReuseInit()
        }
    }

    abstract fun initView()

    /**
     * 重用view需重写此方法对view进行复位操作，防止脏数据展示
     */
    open fun onReuseInit() {

    }

    override fun onDestroy() {
        super.onDestroy()

        if (isReuseView) {
            LayoutHelper.get().cacheView(resourceId, rootView)
        }
    }
}